const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const userId = wxContext.OPENID;
  
  if (!userId) {
    return {
      code: 1,
      message: '用户未登录'
    };
  }
  
  try {
    const { timeSlotKey } = event;
    
    // 参数验证
    if (!timeSlotKey) {
      return {
        code: 2,
        message: '参数不完整'
      };
    }
    
    // 从匹配池中移除
    const result = await db.collection('matching_pool')
      .where({ userId, timeSlotKey })
      .remove();
    
    if (result.stats.removed > 0) {
      return { 
        code: 0, 
        message: '已退出匹配',
        data: {
          removed: result.stats.removed
        }
      };
    } else {
      return { 
        code: 1, 
        message: '未找到匹配记录' 
      };
    }
  } catch (error) {
    console.error('退出匹配池出错:', error);
    return { 
      code: 500, 
      message: '服务器错误',
      error: error.message 
    };
  }
};